﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace WebApp.Common.EFQuery
{
    /// <summary>
    /// 这个ModelBinder只取排序、分页值，查询输入项的值由其子类获取
    /// </summary>
    public partial class QueryModelBinder : System.Web.Mvc.IModelBinder
    {
        /// <summary>
        /// 读取排序、分页等条件，返回QueryModel
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (QueryModel)(bindingContext.Model ?? new QueryModel());
            var dict = controllerContext.HttpContext.Request.Params;

            const string paramOrderBy = "order";
            const string paramSortField = "sort";
            model.PageNumber = 1;//默认显示第一页
            model.PerPageCount = 20;//默认每页显示20条
            model.Items = new List<ConditionItem>();
            string tmp = dict[paramSortField];
            int number = 0;

            if (!string.IsNullOrEmpty(tmp))
            {
                model.OrderBy = tmp;
                tmp = dict[paramOrderBy];
                if (!string.IsNullOrEmpty(tmp))
                {
                    model.OrderBy += " " + tmp;
                }
                else
                {
                    model.OrderBy += " asc";
                }
            }

            tmp = dict["page"];
            if (!string.IsNullOrEmpty(tmp) && int.TryParse(tmp, out number))
            {
                model.PageNumber = number;
            }
            tmp = dict["rows"];
            if (!string.IsNullOrEmpty(tmp) && int.TryParse(tmp, out number))
            {
                model.PerPageCount = number;
            }

            return model;
        }
    }
}
